﻿using FluentAssertions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NewRetail.Application.Components.WeChat.CardVoucher.Entity;
using NewRetail.Application.Components.WeChat.CardVoucher.Model;
using NewRetail.Application.Components.WeChat.CardVoucher.Services;
using NewRetail.Application.Components.WeChat.Model;
using NewRetail.Application.Core;
using SKIT.FlurlHttpClient.Wechat.TenpayV3.Models;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace NewRetail.Api.Controllers.WeChatControllers
{
    /// <summary>
    /// 微信卡券
    /// </summary>
    [NewRetailRoute("wechat-cardvoucher")]
    public class WeChatCardVoucherController : BaseController<CardVoucherInfo>
    {
        #region Field
        public readonly ICardVoucherService _cardVoucherService;
        private readonly ILogger _logger;
        #endregion

        #region Constructor
        public WeChatCardVoucherController(ICardVoucherService cardVoucherService, ILogger<WeChatCardVoucherController> logger)
        {
            _cardVoucherService = cardVoucherService;
            _logger = logger;
        }
        #endregion

        #region method

        #region 创建代金券批次
        /// <summary>
        /// 创建代金券批次
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>

        [HttpPost("wechat-createmarketingfavorstock")]
        public async Task<ResponseEntity<string>> CreateMarketingFavorStock([FromBody] MarketingFavorStockCreateInputDto inputDto)
        {
            inputDto.Should().NotBeNull();
            var ret = new ResponseEntity<string>();
            try
            {
                var result = await _cardVoucherService.CreateMarketingFavorStockAsync(inputDto);
                if (string.IsNullOrEmpty(result.Item1))
                    ret.SetError("创建代金券失败！" + result.Item2);
                ret.SetData(result.Item1);
            }
            catch(Exception e)
            {
                ret.SetError("创建代金券失败！" + e.Message);
                _logger.LogError(e.Message);
            }

            return ret;
        }
        #endregion

        #region 激活代金券批次
        /// <summary>
        /// 激活代金券批次。如果是预充值代金券，激活时会从商户账户余额中锁定本批次的营销资金
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>

        [HttpPost("wechat-activemarketingfavorstock")]
        public async Task<ResponseEntity<string>> ActiveMarketingFavorStock([FromBody] MarketingFavorStockActiveInputDto inputDto)
        {

            var ret = new ResponseEntity<string>();
            try
            {
                var result = await _cardVoucherService.ActiveMarketingFavorStockAsync(inputDto);
                if (string.IsNullOrEmpty(result.Item1))
                    ret.SetError("激活代金券失败！" + result.Item2);
                ret.SetData(result.Item1);
            }
            catch (Exception e)
            {
                ret.SetError("激活代金券失败！" + e.Message);
                _logger.LogError(e.Message);
            }

            return ret;
        }
        #endregion

        #region 发放代金券批次
        /// <summary>
        /// 发放代金券批次。
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>

        [HttpPost("wechat-sendmarketingfavorstock")]
        public async Task<ResponseEntity<string>> SendMarketingFavorStock([FromBody] MarketingFavorStockSendInputDto inputDto)
        {
            var ret = new ResponseEntity<string>();
            try
            {
                var result = await _cardVoucherService.SendMarketingFavorStockAsync(inputDto);
                if (string.IsNullOrEmpty(result.Item1))
                    ret.SetError("发放代金券失败！" + result.Item2);
                ret.SetData(result.Item1);
            }
            catch (Exception e)
            {
                ret.SetError("发放代金券失败！" + e.Message);
                _logger.LogError(e.Message);
            }

            return ret;
        }
        #endregion

        #region 条件查询批次列表
        /// <summary>
        /// 条件查询批次列表
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>

        [HttpGet("wechat-querymarketingfavorstock")]
        public async Task<QueryMarketingFavorStocksResponse> QueryMarketingFavorStock(MarketingFavorStockQueryInputDto inputDto)
        {
            var result = await _cardVoucherService.QueryMarketingFavorStockAsync(inputDto);
            
            return result;
        }
        #endregion

        #region 查询批次详情
        /// <summary>
        /// 查询批次详情
        /// </summary>
        /// <param name="merchantId"></param>
        /// <param name="stockId"></param>
        /// <returns></returns>

        [HttpGet("wechat-getmarketingfavorstockbystockid")]
        public async Task<GetMarketingFavorStockByStockIdResponse> GetMarketingFavorStockByStockId(string merchantId, string stockId)
        {
            var result = await _cardVoucherService.GetMarketingFavorStockByStockIdAsync(merchantId, stockId);

            return result;
        }
        #endregion

        #region 添加代金券批次(将商户后台生成的券保存在库里以备后续使用)
        /// <summary>
        /// 添加代金券批次(将商户后台生成的券保存在库里以备后续使用)
        /// </summary>
        /// <param name="stockId"></param>
        /// <returns></returns>
        [HttpPost("wechat-savemarketingfavorstock")]
        public async Task<ResponseEntity<CardVoucherInfo>> SaveMarketingFavorStock([FromBody] string stockId)
        {                           
            var ret = new ResponseEntity<CardVoucherInfo>();
            try
            {
                if (string.IsNullOrEmpty(stockId))
                {
                    ret.Data = null;
                    ret.SetError("保存代金券失败，批次号不能为空！");
                }
                else
                {
                    var result = await _cardVoucherService.SaveOffLineMarketingFavorStockAsync(stockId);
                    if (!string.IsNullOrEmpty(result.Item2))
                    {
                        ret.Data = null;
                        ret.SetError("保存代金券失败！" + result.Item2);
                    }
                    ret.SetData(string.IsNullOrEmpty(result.Item1.stockId) ? null : result.Item1);
                }
            }
            catch (Exception e)
            {
                ret.Data = null;
                ret.SetError("保存代金券失败！" + e.Message);
                _logger.LogError(e.Message);
            }

            return ret;
        }
        #endregion

        #region 查询代金券详情
        /// <summary>
        /// 查询代金券详情
        /// </summary>
        /// <param name="couponId"></param>
        /// <param name="openId"></param>
        /// <returns></returns>

        [HttpGet("wechat-getmarketingfavorusercouponsbyid")]
        public async Task<ResponseEntity<GetMarketingFavorUserCouponByCouponIdResponse>> GetMarketingFavorUserCouponsById(string couponId, string openId)
        {

            var ret = new ResponseEntity<GetMarketingFavorUserCouponByCouponIdResponse>();
            try
            {
                var result = await _cardVoucherService.GetMarketingFavorUserCouponsAsync(couponId, openId);
                if (!string.IsNullOrEmpty(result.ErrorMessage))
                {
                    ret.Data = null;
                    ret.SetError("查询代金券详情失败！" + result.ErrorMessage);
                }
                ret.SetData(result);
            }
            catch (Exception e)
            {
                ret.Data = null;
                ret.SetError("查询代金券详情失败！" + e.Message);
                _logger.LogError(e.Message);
            }

            return ret;
        }
        #endregion

        #region 根据商户号、openid查用户的券
        /// <summary>
        /// 根据商户号、openid查用户的券
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>

        [HttpGet("wechat-querymarketingfavorusercoupons")]
        public async Task<ResponseEntity<QueryMarketingFavorUserCouponsResponse>> QueryMarketingFavorUserCoupons(string openId)
        {

            var ret = new ResponseEntity<QueryMarketingFavorUserCouponsResponse>();
            try
            {
                var result = await _cardVoucherService.QueryMarketingFavorUserCouponsAsync(openId);
                if (!string.IsNullOrEmpty(result.ErrorMessage))
                {
                    ret.Data = null;
                    ret.SetError("根据商户号、openid查用户的券失败！" + result.ErrorMessage);
                }
                ret.SetData(result);
            }
            catch (Exception e)
            {
                ret.Data = null;
                ret.SetError("根据商户号、openid查用户的券失败！" + e.Message);
                _logger.LogError(e.Message);
            }

            return ret;
        }
        #endregion

        #region 根据openid查用户的券并修改本地状态
        /// <summary>
        /// 根据openid查用户的券并修改本地状态
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>

        [HttpPost("wechat-querysavemarketingfavorusercoupons")]
        public async Task<ResponseEntity<string>> QuerySaveMarketingFavorUserCoupons(string openId)
        {
            var ret = new ResponseEntity<string>();
            if (string.IsNullOrEmpty(openId))
            {
                ret.Data = null;
                ret.SetError("openId不允许空！");
                return ret;
            }
            try
            {
                var result = await _cardVoucherService.QuerySaveMarketingFavorUserCouponsAsync(openId);
                if (!string.IsNullOrEmpty(result.Item2))
                {
                    ret.Data = null;
                    ret.SetError("根据openid查用户的券并修改本地状态失败！失败券id:" + result.Item2);
                }
                ret.SetData(string.Join(",", result.Item1));
            }
            catch (Exception e)
            {
                ret.Data = null;
                ret.SetError("根据openid查用户的券并修改本地状态失败！" + e.Message);
                _logger.LogError(e.Message);
            }

            return ret;
        }
        #endregion

        #region 查询代金券批次及领用详情信息
        /// <summary>
        /// 查询代金券批次及领用详情信息
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>

        [HttpPost("wechat-querymarketingfavorallusercoupons")]
        public async Task<ResponseEntity<HeaderResult<List<MarketingFavorStockUserCouponsDto>>>> QueryMarketingFavorAllUserCoupons([FromBody]MarketingFavorStockUserCouponsInputDto inputDto)
        {

            var ret = new ResponseEntity<HeaderResult<List<MarketingFavorStockUserCouponsDto>>>();
            try
            {
                var result = await _cardVoucherService.QueryMarketingFavorAllUserCouponsAsync(inputDto);
                if (!string.IsNullOrEmpty(result.Item2))
                {
                    ret.Data = null;
                    ret.SetError("查询代金券批次及领用详情信息失败！" + result.Item2);
                }
                var headerResult = new HeaderResult<List<MarketingFavorStockUserCouponsDto>>()
                {
                    IsSucceed = true,
                    Result = result.Item1,
                    IsLastPage = result.Item3
                };
                ret.SetData(headerResult);
            }
            catch (Exception e)
            {
                ret.Data = null;
                ret.SetError("查询代金券批次及领用详情信息失败！" + e.Message);
                _logger.LogError(e.Message);
            }

            return ret;
        }
        #endregion       

        #region 保存
        [Obsolete]
#pragma warning disable CS0809 // 过时成员重写未过时成员
        public override async Task<ResponseEntity<CardVoucherInfo>> Save([FromBody] CardVoucherInfo cardVoucherInfo)
#pragma warning restore CS0809 // 过时成员重写未过时成员
        {
            return await Task.Run(()=> new ResponseEntity<CardVoucherInfo>());                            
        }
        #endregion

        #region 会员卡相关

        #region 创建会员卡模板
        /// <summary>
        /// 创建会员卡模板
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>

        //[HttpPost("wechat-createmarketingmembercard")]
        //public async Task<ResponseEntity<string>> CreateMarketingMemberCard([FromBody] MarketingMemberCardCreateInputDto inputDto)
        //{
        //    inputDto.Should().NotBeNull();
        //    var ret = new ResponseEntity<string>();
        //    try
        //    {
        //        var result = await _cardVoucherService.CreateMarketingMemberCardAsync(inputDto);
        //        if (string.IsNullOrEmpty(result.Item1))
        //            ret.SetError("创建会员卡模板失败！" + result.Item2);
        //        ret.SetData(result.Item1);
        //    }
        //    catch (Exception e)
        //    {
        //        ret.SetError("创建会员卡模板失败！" + e.Message);
        //        _logger.LogError(e.Message);
        //    }

        //    return ret;
        //}
        #endregion

        #endregion

        #endregion
    }
}
